package com.feihong.txgw.ui.activity.user;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.CacheUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.SpanUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.inter.contract.login.ILoginContract;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.model.bean.user.User;
import com.feihong.txgw.observer.SmsObserver;
import com.feihong.txgw.tx_precenter.LoginMainPrecenter;
import com.feihong.txgw.ui.activity.HomeActivity;
import com.feihong.txgw.ui.activity.setting.ServiceMessageActivity;
import com.feihong.txgw.ui.mvp.BaseMVPCompateActivity;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;
import com.feihong.txgw.utils.ToastUtils;
import com.feihong.txgw.utils.UserLoginInfo;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import butterknife.BindView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by Sabirjan on 2017/6/13.
 * TXGW.
 * 飞宏电子
 * 用户手机号登录 （短信验证码来登录）
 */

@RuntimePermissions
public class LoginActivity extends BaseMVPCompateActivity<ILoginContract.AbLoginMainPrecenter> implements ILoginContract.ILoginMainView {

    /**
     * 验证码按钮
     */
    @BindView(R.id.codeTimmer)
    TextView codeTimmer;
    /**
     * 手机号
     */
    @BindView(R.id.edit_phonenum)
    EditText editPhonenum;
    /**
     * 登录页
     */
    @BindView(R.id.activityLogin)
    LinearLayout activityLogin;
    /**
     * 验证码
     */
    @BindView(R.id.regionCode)
    EditText regionCode;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_pagetitle)
    TextView txtPagetitle;
    /**
     * 用户协议
     */
    @BindView(R.id.login_agreement_terms)
    TextView loginAgreementTerms;
    @BindView(R.id.login_help)
    TextView loginHelp;
    @BindView(R.id.login_checkbox)
    CheckBox loginCheckbox;
    @BindView(R.id.login_btn)
    Button loginBtn;

    private String phoneNo;
    /**
     * 验证码倒计时
     */
    private CountDownTimer timer;
    /**
     * 登陆接口返回失败信息
     */
    public String loginResult;
    public SPUtils sp;
    private CacheUtils cache;

    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_login;
    }

    private void textChange() {
        editPhonenum.addTextChangedListener(watcher);
        regionCode.addTextChangedListener(watcher);
    }

    TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s != null && s.toString().length() == 11) {
                //两次输入的手机号码不同,可以点击发送验证码
                LogUtils.i(TAG + ":-------手机号码CACHE----------" + cache.getString(s.toString()));
                if (cache.getString(s.toString()) == null) {
                    if (timer != null) {
                        timer.cancel();
                        codeTimmer.setText("获取验证码");
                        codeTimmer.setEnabled(true);
                    }
                }
            }

            if (s != null && editPhonenum.getText().length() == 11 && s.toString().length() == 6) {
                KeyboardUtils.hideSoftInput(LoginActivity.this);
            }
        }
    };

    /***
     * @param view
     */
    public void btnRegisterClick(View view) {

        KeyboardUtils.hideSoftInput(LoginActivity.this);

        phoneNo = editPhonenum.getText().toString().trim();

        //电话号码正则判断
        boolean isPhoneNum = RegexUtils.isMobileExact(phoneNo);

        if (isPhoneNum) {
            //验证码倒计时
            timer = new CountDownTimer(60000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    if (activityIsDestory()) {
                        return;
                    }
                    codeTimmer.setText("倒计时:" + millisUntilFinished / 1000 + "S");
                    codeTimmer.setEnabled(false);
                }

                @Override
                public void onFinish() {
                    if (activityIsDestory()) {
                        return;
                    }
                    codeTimmer.setText("重新获取");
                    codeTimmer.setEnabled(true);
                    cache.remove(phoneNo);
                }
            }.start();

            cache.put(phoneNo, phoneNo);
            LoginActivityPermissionsDispatcher.onNeedsReadSmsPermissionWithCheck(this);
            //发送验证码
            mPresenter.getTelCode(phoneNo, "");
        } else {
            if (phoneNo == null || "".equals(phoneNo)) {
                ToastUtils.getInstance().showShortToastAutoColor("请输入手机号码", 0);
            } else {
                ToastUtils.getInstance().showShortToast("请输入正确的手机号码");
            }
        }
    }

    private SmsObserver smsObserver = new SmsObserver(new Handler(), this, new SmsObserver.SmsListener() {
        @Override
        public void onResult(String smsContent) {
            if (activityIsDestory()) {
                return;
            }
            regionCode.setText(smsContent);
        }
    }, "10473", "");


    /***
     * 测试登录
     * @param view
     */
    public void btnLoginClick(View view) {

        //重新加载号码输入框
        phoneNo = editPhonenum.getText().toString().trim();
        sp.put("phoneNum", phoneNo);

        String code = regionCode.getText().toString().trim();

        boolean isCode = RegexUtils.isMatch("\\d{6}", code);

        if (code == null || "".equals(code) || !isCode) {

            ToastUtils.getInstance().showShortToastAutoColor("请输6位手机验证码", 0);

        } else {

            showProgressDialog("正在登陆....");
            loginBtn.setClickable(false);
            mPresenter.userLogin(phoneNo,code);
            //登录或注册
        }
    }

    Handler mhanlder = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (activityIsDestory()) {
                return;
            }
            dismissProgressDialog();
            if (msg.what < 50) {
                LoginMessage loginMessage = new LoginMessage();
                loginMessage.setAction(LoginMessage.ACTION_LOGIN);
                loginMessage.setUser_phone(phoneNo);
                EventBus.getDefault().post(loginMessage);
                if(isForceLogin){
                    Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                    startActivity(intent);
                }
                finish();
                cache.clear();
            } else if (msg.what < 100) {
//                showToast(loginResult);
//                MyToast.showShortToastImg(getApplication(), ""+loginResult);
                ToastUtils.getInstance().showShortToast("" + loginResult);
            } else {
                ToastUtils.getInstance().showShortToast("登陆失败,请稍后尝试~");
            }
//                MyToast.showShortToastImg(getApplication(), "登陆失败,请重试~");
        }
    };


    private void queryDeliveryAdr() {
        mPresenter.getDeliverAdr();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            LoginMessage loginMessage = new LoginMessage();
            loginMessage.setAction(LoginMessage.ACTION_CANCEL);
            EventBus.getDefault().post(loginMessage);
            chackActivityState();
            if(!isRestartActivity && isForceLogin){
                Intent intent = new Intent(this,HomeActivity.class);
                startActivity(intent);
            }
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 是否是强制登录
     */
    private boolean isForceLogin = false;
    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        cache = CacheUtils.getInstance("loginPhoneNum");
        cache.clear();
        textChange();

        setBackButtonFinish();
        setPageTitle(getResources().getString(R.string.login_title));

        sp = SPUtils.getInstance("userInfoEdit");
        editPhonenum.setText(sp.getString("phoneNum"));


        //用户协议
        String strAgreement = getResources().getString(R.string.login_agreement_terms);

        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Intent intent = new Intent();
                intent.setClass(getApplication(), LoginRegAgrement.class);
                startActivity(intent);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(getResources().getColor(R.color.login_getCode));
                ds.setUnderlineText(false);
            }
        };

        //用户协议点击事件
        clickAbleMethod(loginAgreementTerms, clickableSpan, strAgreement, 2);

        //遇到问题?联系客服
        String strHelp = getResources().getString(R.string.login_request_help);

        ClickableSpan clickHelp = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Intent intent = new Intent();
                intent.setClass(getApplication(), ServiceMessageActivity.class);
                startActivity(intent);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(getResources().getColor(R.color.login_getCode));
                ds.setUnderlineText(false);
            }
        };

        //联系客服点击事件
        clickAbleMethod(loginHelp, clickHelp, strHelp, strHelp.length() - 4);

    }

    //clickableSpan设置属性
    private int clickableSpanMethod(TextView textView) {
        // 响应点击事件的话必须设置以下属性
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        // 去掉点击事件后的高亮
        textView.setHighlightColor(ContextCompat.getColor(this, android.R.color.transparent));
        //文字居中对齐
        return textView.getLineHeight();
    }

    //clickableSpan点击事件
    public void clickAbleMethod(TextView textView, ClickableSpan clickSpan, String strInfo, int start) {
        int lineHeight = clickableSpanMethod(textView);
        textView.setText(new SpanUtils().append(strInfo.substring(0, start))
                .append(strInfo.substring(start)).setClickSpan(clickSpan)
//        .setSpans(new ForegroundColorSpan(getResources().getColor(R.color.black_text)))
                .setLineHeight(2 * lineHeight, SpanUtils.ALIGN_CENTER)
                .create());
    }

    @Override
    public void doUserLogin(LoginMessage loginMessage) {
        super.doUserLogin(loginMessage);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mhanlder != null && mhanlder.getLooper() == Looper.getMainLooper()) {
            mhanlder.removeCallbacksAndMessages(null);
        }
        if (smsObserver != null) {
            getContentResolver().unregisterContentObserver(smsObserver);
        }
    }
    /**
     * 是否是强制退出
     */
    public static final String isFrouceLogoutKey = "forceLogOut";
    @Override
    public void bindData() {

        isForceLogin = getIntent().getBooleanExtra(isFrouceLogoutKey,false);

    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    public void btnAgreement(View view) {

        if (!loginCheckbox.isChecked()) {
            ToastUtils.getInstance().showShortToast("请同意《用户协议》后登陆");
            loginBtn.setEnabled(false);
        } else {
            loginBtn.setEnabled(true);
        }
    }

    @NeedsPermission({Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS})
    void onNeedsReadSmsPermission() {
        getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, smsObserver);
    }

    @NeedsPermission({Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS})
    void onPermissionDenied() {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.i(TAG, "onRequestPermissionsResult: 权限---允许");
        LoginActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    public void getTelCodeResult(String result) {
        try {
            if (activityIsDestory()) {
                return;
            }
            JSONObject json = JSONObject.parseObject(result);

            //成功
            if ("200".equals("" + json.get("code").toString())) {
                ToastUtils.getInstance().showShortToast("发送成功!");
            } else {
                ToastUtils.getInstance().showShortToast("" + json.getString("msg"));
                timer.cancel();
                codeTimmer.setText("重新获取");
                codeTimmer.setEnabled(true);
            }
        } catch (Exception ex) {

        }
    }

    @Override
    public void getTelCodeError() {
        showSystemToast("请检查网络");
        timer.cancel();
        codeTimmer.setText("重新获取");
        codeTimmer.setEnabled(true);
    }

    @Override
    public void userLoginResult(String result) {
        try {
            if (activityIsDestory()) {
                return;
            }
            dismissProgressDialog();
            loginBtn.setClickable(true);
            LogUtils.i(TAG + result);

            JSONObject json = JSONObject.parseObject(result);

            //成功
            if ("200".equals("" + json.get("code").toString())) {

                JSONObject jsonData = JSONObject.parseObject(json.getString("data"));

                //登陆成功,保存用户信息
                User user = new User();
                user.setUserID(jsonData.getString("user_id"));
                user.setUserPhone(jsonData.getString("mobile"));
                user.setUserName(jsonData.getString("user_name"));
                user.setUserSex(jsonData.getString("sex"));
                //头像
                user.setUserPic(jsonData.getString("img_head"));

                UserLoginInfo.updateUserToken(jsonData.getString("token"));

                UserLoginInfo.saveUserLoginInfo(user);

                queryDeliveryAdr();
                mhanlder.sendEmptyMessage(1);
            } else {
                loginResult = json.get("msg").toString();
                mhanlder.sendEmptyMessage(51);
            }
        } catch (Exception err) {

        }
    }

    @Override
    public void usrLoginError() {

        dismissProgressDialog();
        loginBtn.setClickable(true);
        mhanlder.sendEmptyMessage(101);
    }

    @Override
    public void loadDataComplated() {

    }

    @Override
    public void loadDataError() {

    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return LoginMainPrecenter.create();
    }
}
